import { fetch } from 'plugins/axios'
import { downExcel } from 'plugins/common'
import { date } from 'quasar'

export function loadFilters ({state, commit}) {
  return new Promise((resolve, reject) => {
    fetch('/hosts/host_filters/', {}).then((response) => {
      commit('filterSuccess', response)
      resolve()
    }).catch((error) => {
      console.log(error)
    })
  })
}

export function loadHeaders ({state, commit}) {
  return new Promise((resolve, reject) => {
    fetch('/getmodels/', {
      appname: 'cmdb',
      modelname: 'Host'
    }).then((response) => {
      commit('headerSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function loadTable ({state, commit}) {
  return new Promise((resolve, reject) => {
    state.loading = true
    const {sortBy, descending, page, rowsPerPage} = state.serverPagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/hosts/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search,
      status: state.status.value,
      asset_type: state.type.value,
      env__env: state.env.value,
      env__clouds: state.clouds.value,
      create_time_after: date.formatDate(state.sdate, 'YYYY-MM-DD'),
      create_time_before: date.formatDate(state.edate, 'YYYY-MM-DD')
    }).then((response) => {
      commit('loadTableSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function loadBtn ({state}) {
  state.loadsync = true
  fetch('/hosts/host_sync/', {
  }).then((response) => {
    alert(JSON.parse(response))
    state.loadsync = false
    this.dispatch('listHost/loadTable')
  }).catch((error) => {
    alert(error.response.data)
    state.loadsync = false
    this.loader = null
  })
}

export function fileDownload ({state}) {
  downExcel(state.columns, state.tableData)
}
